package com.micai.springboot.controller.admin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.micai.springboot.base.BaseController;
import com.micai.springboot.base.servlet.ServletUtil;
import com.micai.springboot.dto.RoleDto;
import com.micai.springboot.dto.RoleMenuDto;
import com.micai.springboot.param.RoleMenuParam;
import com.micai.springboot.service.RoleMenuService;
import com.micai.springboot.service.RoleService;
import com.micai.springboot.service.UserRoleService;
import com.micai.springboot.task.AsyncTask;
import com.micai.springboot.util.MessageUtils;
import com.micai.springboot.view.PoiExcelExport;
import com.micai.springboot.vo.RoleVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述：角色管理
 * <p>
 * Author: 赵新国
 * Date: 2017/11/14 15:21
 */
@Controller
@RequestMapping("/admin/role")
public class AdminRoleController extends BaseController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private AsyncTask asyncTask;

    /**
     * 分页查询角色列表
     * @param model
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(@RequestParam(value="pageNum", defaultValue="1") int pageNum,
                       @RequestParam(value="pageSize", defaultValue="10") int pageSize,
                       @RequestParam(required = false) String searchParam,
                       @RequestParam(required = false) String startDate,
                       @RequestParam(required = false) String endDate,Model model) {
        Page<RoleDto> roleDtos = roleService.getRoleByPage(pageNum, pageSize, searchParam, startDate, endDate);
        if (roleDtos == null) {
            roleDtos = new Page<RoleDto>();
        }
        PageInfo<RoleDto> pageInfo = new PageInfo<RoleDto>(roleDtos);
        model.addAttribute("page", pageInfo);
        // 参数回显
        model.addAttribute("name", searchParam);
        model.addAttribute("startDate", startDate);
        model.addAttribute("endDate", endDate);
        return "admin/role/roleList";
    }

    /**
     * 保存角色信息
     *
     * @param roleVo
     * @return
     */
    @PostMapping(value = "/save")
    @ResponseBody
    public Map<String, Object> save(@ModelAttribute RoleVo roleVo) {
        Map<String, Object> retMap = MessageUtils.success();
        try {
            RoleDto roleDto = new RoleDto();
            BeanUtils.copyProperties(roleVo, roleDto);
            roleDto.setCreator(getId());
            roleDto.setModifier(getId());
            if (roleService.save(roleDto) == 1) {
                retMap = MessageUtils.success("保存成功");
                return retMap;
            }
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

    /**
     * 根据ID查询角色信息
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/get/{id}")
    @ResponseBody
    public Map<String, Object> get(@PathVariable("id") Long id) {
        Map<String, Object> retMap = MessageUtils.success();
        try {
            RoleDto roleDto = roleService.getRoleById(id);
            if (roleDto != null) {
                retMap.put("roleDto", roleDto);
                return retMap;
            }
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

    /**
     * 修改角色信息
     *
     * @param roleVo
     * @return
     */
    @PostMapping(value = "/edit")
    @ResponseBody
    public Map<String, Object> edit(@ModelAttribute RoleVo roleVo) {
        Map<String, Object> retMap = null;
        try {
            RoleDto roleDto = roleService.getRoleById(roleVo.getId());
            if (roleDto == null) {
                retMap = MessageUtils.error("修改失败");
                return retMap;
            }
            BeanUtils.copyProperties(roleVo, roleDto);
            roleDto.setModifier(getId());
            // 修改角色
            if (roleService.update(roleDto) == 1) {
                retMap = MessageUtils.success("修改成功");
                return retMap;
            }
        } catch (Exception e) {
            retMap = MessageUtils.error("修改失败");
        }
        return retMap;
    }

    /**
     * 导出角色信息
     *
     * @param searchParam
     * @return
     */
    @GetMapping(value = "/export")
    public void export(@RequestParam String searchParam, HttpServletRequest request, HttpServletResponse response) {
        long start = System.currentTimeMillis();
        String fileName = "角色数据.xls";
        ServletUtil su = new ServletUtil(fileName, request, response);
        su.poiExcelServlet();
        String[] heads = {"角色名称","角色编码"};
        String[] cols = {"name","code"};
        int[] numerics = {2};
        List<RoleDto> roleDtos = roleService.getRoleByParam(searchParam);
        if (roleDtos == null || roleDtos.isEmpty()) {
            return;
        }
        ServletUtil suresp = new ServletUtil(response);
        PoiExcelExport pee = new PoiExcelExport(fileName, heads, cols, roleDtos, numerics, suresp.getOut());
        pee.exportExcel();
        long end = System.currentTimeMillis();
        logger.info("导出Excel耗时：" + (end -start) + " 毫秒.");
    }

    /**
     * 查询全部角色列表
     * @param pageNum
     * @param pageSize
     * @param searchParam
     * @return
     */
    @GetMapping(value = "/getRoles")
    @ResponseBody
    public Map<String, Object> getRoles(@RequestParam(value="pageNum", defaultValue="1") int pageNum,
                                            @RequestParam(value="pageSize", defaultValue="10") int pageSize,
                                            @RequestParam(required = false) String searchParam) {
        Map<String, Object> retMap = MessageUtils.success();
        List<RoleDto> roleDtos = roleService.getRoleByParam(searchParam);
        if (roleDtos != null) {
            retMap.put("roleDtos", roleDtos);
        } else {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

    /**
     * 根据ID批量删除角色信息
     *
     * @param ids
     * @return
     */
    @PostMapping(value = "/deleteBatch")
    @ResponseBody
    public Map<String, Object> deleteBatch(@RequestParam("ids[]") List<Long> ids) {
        Map<String, Object> retMap = null;
        try {
            for (Long id : ids) {
                // 删除角色之前验证角色是否已经被分配
                if (userRoleService.getRoleIdsByRoleId(id) > 0) {
                    retMap = MessageUtils.error("该角色已经被分配，不能删除");
                    return retMap;
                }
                // 删除角色之前验证角色是否已经分配了菜单
                if (roleMenuService.getRoleIdsByRoleId(id) > 0) {
                    retMap = MessageUtils.error("该角色已经分配菜单，不能删除");
                    return retMap;
                }
                // 删除角色
                if (roleService.deleteById(id)) {
                    retMap = MessageUtils.success("删除成功");
                    return retMap;
                }
            }
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

    /**
     * 根据用户ID删除角色信息
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete/{id}")
    @ResponseBody
    public Map<String, Object> delete(@PathVariable("id") Long id) {
        Map<String, Object> retMap = null;
        try {
            // 删除角色之前验证角色是否已经被分配
            if (userRoleService.getRoleIdsByRoleId(id) > 0) {
                retMap = MessageUtils.error("该角色已经被分配，不能删除");
                return retMap;
            }
            // 删除角色之前验证角色是否已经分配了菜单
            if (roleMenuService.getRoleIdsByRoleId(id) > 0) {
                retMap = MessageUtils.error("该角色已经分配菜单，不能删除");
                return retMap;
            }
            // 删除角色
            if (roleService.deleteById(id)) {
                retMap = MessageUtils.success("删除成功");
                return retMap;
            }
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

    /**
     * 保存角色菜单信息
     * @param roleMenuParam
     * @return
     */
    @PostMapping(value = "/scope")
    @ResponseBody
    public Map<String, Object> scope(@RequestBody RoleMenuParam roleMenuParam) {
        Map<String, Object> retMap = MessageUtils.success();
        try {
            RoleMenuDto roleMenuDto = new RoleMenuDto();
            if (roleMenuParam != null) {
                // 删除当前角色下的所有的历史菜单
                roleMenuService.deleteRoleMenuByRoleId(Long.valueOf(roleMenuParam.getRoleId()));
                // 保存当前角色下的新菜单
                roleMenuParam.getMenuIds().stream().forEach(menuId -> {
                    roleMenuDto.setRoleId(Long.valueOf(roleMenuParam.getRoleId()));
                    roleMenuDto.setMenuId(Long.valueOf(menuId));
                    roleMenuService.save(roleMenuDto);
                });
                // 删除左侧菜单缓存
                List<Long> userIds = userRoleService.getUserIdsByRoleId(Long.valueOf(roleMenuParam.getRoleId()));
                asyncTask.deleteLeftCache(userIds);
                retMap = MessageUtils.success("保存成功");
                return retMap;
            }
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

}
